package com.example.stock.tencent;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.example.stock.entity.Stock;
import com.example.stock.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;

@Slf4j
@Component
@EnableScheduling
public class TencentStockHandler {
//    private String urlPara = "sz002238,sz002413,sh603181,sh000001";
    private HashMap<String, String[]> codeMap = new HashMap<>();
    public final static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    public static final String filePath = "D:\\Stock\\src\\main\\resources\\data\\%s.txt";


//    @Scheduled(cron = "* * * * * *")
//    @PostConstruct
    public void refresh(){
      //  stepAction();
        loadFile("D:\\Stock\\src\\main\\resources\\data\\2024-12-18.txt");
    }
int test = 0;

    List<Map<String, StockBean>> list = new ArrayList<>();

    Map<String, StockBean> lastHighMap = new HashMap<>();

    @Autowired
    private IStockService iStockService;

//    @Scheduled(cron = "*/10 * * * * *")
    public void queryLoading() throws Exception {
        if(lastHighMap.isEmpty()){
            List<StockBean> resultArr = new TencentStockHandler().loadDataByFile("D:\\Stock\\src\\main\\resources\\data\\2024-12-12-P.txt");
            List<StockBean> highArr = new ArrayList<>();
            resultArr.forEach(obj->{
                if(obj.getPriceNow() == obj.getHighLimit()){
                    highArr.add(obj);
                }
            });
            lastHighMap = highArr.stream().collect(Collectors.toMap(StockBean::getCode, Function.identity()));
        }


        String result = HttpClientPool.getHttpClient().get("http://qt.gtimg.cn/q=" + lastHighMap.keySet().stream().collect(Collectors.joining(",")));
        List<StockBean> curBeans = parse(result);
        Map<String, StockBean> collect = curBeans.stream().collect(Collectors.toMap(StockBean::getCode, Function.identity()));
        test = 0;
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化当前时间
        String formattedNow = now.format(formatter);
        for (Map.Entry<String, StockBean> stringStockBeanEntry : collect.entrySet()) {
            String key =stringStockBeanEntry.getKey();
            StockBean value=stringStockBeanEntry.getValue();
            if(list.size()>=11) {
                for (int i = list.size() - 11; i <= list.size() - 1; i++) {
                    Map<String, StockBean> stringStockBeanMap = list.get(i);
                    StockBean stockBean = stringStockBeanMap.get(key);
                    if(value.getPriceNow()>stockBean.getPriceNow() && value.getPriceNow() == value.getHighLimit()){
                        DingDingBot.send(formattedNow+"\n" +stockBean.getName()+"-"+value.getCode()+"已拉至涨停,当前封单量+"+value.getBuyOrders().getOrders().get(0).getQuantity()+"手");
                        test = 4;
                        break;
                    }
                    if(value.getChangePercent() - stockBean.getChangePercent() >= 3){
                        DingDingBot.send(formattedNow+"\n" +stockBean.getName()+"-"+value.getCode()+"在2min钟内快速拉伸"+(value.getChangePercent()-stockBean.getChangePercent())+"%,当前涨幅"+value.getChangePercent()+"%");
                        test = 3;
                        break;
                    }
                }
            }else{
                for (int i = 0; i <= list.size() - 1; i++) {
                    Map<String, StockBean> stringStockBeanMap = list.get(i);
                    StockBean stockBean = stringStockBeanMap.get(key);

                    if(value.getPriceNow() == value.getHighLimit()){
                        DingDingBot.send(formattedNow+"\n" +stockBean.getName()+"-"+value.getCode()+"已拉至涨停,当前封单量+"+value.getBuyOrders().getOrders().get(0).getQuantity()+"手");
                        test = 1;
                        break;
                    }
                    if(value.getChangePercent() - stockBean.getChangePercent() >= 3){
                        DingDingBot.send(formattedNow+"\n" +stockBean.getName()+"-"+value.getCode()+"在开盘快速拉伸"+(value.getChangePercent()-stockBean.getChangePercent())+"%,当前涨幅"+value.getChangePercent()+"%");
                        test = 2;
                        break;
                    }
                }
            }
            if(test>0){
                Console.log(formattedNow+"--",test);
                break;
            }
        }
        list.add(collect);
        if(list.size()>20){
            list.remove(0);
        }
    }




    @Autowired
    private ResourceLoader resourceLoader;
    private void stepAction() {
        List<String[]> data = new ArrayList<>();
        Resource resource = resourceLoader.getResource("classpath:all_stock.csv");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",");
                data.add(fields);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        data.remove(0);
        // 使用Hutool的分组方法
        List<List<String[]>> groupedArray = CollUtil.split(data, 100);
        StringBuilder builder = new StringBuilder();
        // 输出分组后的结果
        int index = 1;
        for (List<String[]> group : groupedArray) {
            String urlPara = group.stream().map(o -> o[0].replace(".", "")).collect(Collectors.joining(","));
            try {
                Console.log(String.format("当前请求第%d组,一共%d组",index++, groupedArray.size()));
                String result = HttpClientPool.getHttpClient().get("http://qt.gtimg.cn/q=" + urlPara);
                builder.append(result);
                Thread.sleep(1000);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


        // 格式化当前时间
        String formattedNow = now.format(formatter);



        String path = String.format(filePath,formattedNow);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
            writer.write(builder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        Console.log("请求写入完成"+path);
        //loadFile(path);
    }

    public void loadFile(String path){
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<StockBean> stockBeans = parse(builder.toString());
//        anylysisP(builder.toString());
        //        List<StockBean> stockBeans = parse(builder.toString());
//
        Date now = DateUtil.date();
        List<Stock> stocks = new ArrayList<>();
        for (int i = 0; i < stockBeans.size(); i++) {
            StockBean stockBean = stockBeans.get(i);
            Stock stock = new Stock();
            BeanUtil.copyProperties(stockBean, stock,"time");
            stock.setCalcTime(now);
            stock.setCalcType(3);
            stocks.add(stock);
        }
        iStockService.saveBatch(stocks);
    }

    public List<StockBean> loadDataByFile(String path){
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return parse(builder.toString());
    }

    public static void main(String[] args) {
        //http://www.360doc.com/content/23/0928/12/7593676_1098299863.shtml
        String ss = "v_sz002717=\"51~岭南股份~002717~4.53~4.12~4.08~3888486~2103770~1784716~4.53~423318~4.52~2413~4.51~1641~4.50~2221~4.49~2385~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~~20241213155609~0.41~9.95~4.53~4.05~4.53/3888486/1706096280~3888486~170610~24.29~-7.09~~4.53~4.05~11.65~72.52~82.46~4.23~4.53~3.71~0.82~431978~4.39~-22.75~-7.52~~~1.28~170609.6280~0.0000~0~ ~GP-A~40.25~-0.22~0.00~-57.18~-8.03~5.20~0.77~39.81~42.01~268.29~1600783105~1820233558~100.00~89.54~1600783105~~~45.19~0.00~~CNY~0~~4.44~3422\";";
//        String ss2 = "v_sz002717=\"51~岭南股份~002717~4.07~4.09~3.90~5528713~2644136~2884577~4.06~13564~4.05~11570~4.04~2659~4.03~3552~4.02~2797~4.07~2886~4.08~10594~4.09~8436~4.10~11722~4.11~1805~~20241210161406~-0.02~-0.49~4.36~3.90~4.07/5528713/2254882424~5528713~225488~34.54~-6.37~~4.36~3.90~11.25~65.15~74.08~3.80~4.50~3.68~1.04~-1301~4.08~-20.44~-6.76~~~1.29~225488.2424~0.0000~0~ ~GP-A~26.01~3.83~0.00~-57.18~-8.03~5.20~0.77~37.50~29.62~230.89~1600783105~1820233558~-1.87~73.93~1600783105~~~33.44~-0.25~~CNY~0~~4.00~18548\";";
//        String ss3 = "v_sz002717=\"51~岭南股份~002717~4.20~4.29~4.20~33243~15195~18048~4.19~241~4.18~1987~4.17~937~4.16~1743~4.15~3788~4.20~9078~4.21~176~4.22~1456~4.23~765~4.24~1434~~20241212092721~-0.09~-2.10~4.20~4.20~4.20/33243/13962060~33243~1396~0.21~-6.58~~4.20~4.20~0.00~67.23~76.45~3.92~4.72~3.86~0.00~-4213~4.20~-21.10~-6.98~~~1.29~1396.2060~0.0000~0~ ~GP-A~30.03~-11.39~0.00~-57.18~-8.03~5.20~0.77~32.49~44.83~250.00~1600783105~1820233558~-19.50~71.43~1600783105~~~36.36~-2.10~~CNY~0~~4.29~-16725\";";
//        String ss4 = "v_sz002717=\"51~岭南股份~002717~4.13~4.29~4.20~399227~186020~211561~4.13~7787~4.12~9951~4.11~11407~4.10~27864~4.09~5117~4.14~15~4.15~1462~4.16~297~4.17~2568~4.18~2514~~20241212093424~-0.16~-3.73~4.21~4.12~4.13/399227/166486687~399227~16649~2.49~-6.47~~4.21~4.12~2.10~66.11~75.18~3.86~4.72~3.86~3.46~55270~4.17~-20.74~-6.86~~~1.29~16648.6687~0.0000~0~ ~GP-A~27.86~-12.87~0.00~-57.18~-8.03~5.20~0.77~30.28~42.41~244.17~1600783105~1820233558~80.12~68.57~1600783105~~~34.09~-3.73~~CNY~0~~4.08~7084\";";
        new TencentStockHandler().parse(ss);
        //{"code":"sh600439","name":"瑞贝卡","now":4.3,"max":4.32,"min":4.29,"avg":4.31,"volume":17604,"turnover":758.0133,"outPan":9136,"inPan":6760,"buyOrders":{"orders":[{"price":4.3,"quantity":312},{"price":4.29,"quantity":1049},{"price":4.28,"quantity":1596},{"price":4.27,"quantity":2084},{"price":4.26,"quantity":2357}]},"sellOrders":{"orders":[{"price":4.31,"quantity":186},{"price":4.32,"quantity":71},{"price":4.33,"quantity":320},{"price":4.34,"quantity":391},{"price":4.35,"quantity":610}]},"time":"20241211093052","change":-0.04,"changePercent":-0.92,"amplitude":0.69,"peRatioTTM":699.93,"pbRatio":1.78,"totalMarketCap":48.68,"circulatingCap":48.68,"dynamicPeRatio":366.75,"staticPeRatio":395.66,"volumeCompare":4.53,"exchange":0.16}
//        new TencentStockHandler().loadFile("E:\\JavaProject\\stock\\src\\main\\resources\\data\\2024-12-12-P.txt");
    }

    private List<StockBean> parse(String result) {
        List<StockBean> resultArr = new ArrayList<>();
        String[] lines = result.split("\n");
        for (String line : lines) {
            String code = line.substring(line.indexOf("_") + 1, line.indexOf("="));
            String dataStr = line.substring(line.indexOf("=") + 2, line.length() - 2);
            String[] values = dataStr.split("~");
            StockBean bean = new StockBean(code, codeMap);
            bean.setName(values[1]); //名称
            bean.setPriceNow(NumUtil.change(values[3])); //现价
            bean.setPriceChange(NumUtil.change(values[31])); //涨跌
            bean.setChangePercent(NumUtil.change(values[32])); //涨跌%
            bean.setCalcTime(values[30]); //时间
            bean.setPriceMax(NumUtil.change(values[33]));//最高
            bean.setPriceMin(NumUtil.change(values[34]));//最低
            bean.setPriceAvg(NumUtil.change(values[51]));//均价
            bean.setVolume(Long.parseLong(values[6])); //成交量
            bean.setOutPan(Long.parseLong(values[7])); //外盘
            bean.setInPan(Long.parseLong(values[8]));  //内盘
            bean.setTurnover(NumUtil.change(values[57])); //成交额
            StockBean.OrderBook buyOrderBook = new StockBean.OrderBook();
            List<StockBean.Order> buyOrders = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                StockBean.Order order = new StockBean.Order(NumUtil.change(values[9 + i * 2]), Integer.parseInt(values[9 + i * 2 + 1]));
                buyOrders.add(order);
            }
            buyOrderBook.setOrders(buyOrders);
            bean.setBuyOrders(buyOrderBook);

            StockBean.OrderBook saleOrderBook = new StockBean.OrderBook();
            List<StockBean.Order> saleOrders = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                StockBean.Order order = new StockBean.Order(NumUtil.change(values[19 + i * 2]), Integer.parseInt(values[19 + i * 2 + 1]));
                saleOrders.add(order);
            }
            saleOrderBook.setOrders(saleOrders);
            bean.setSellOrders(saleOrderBook);

            bean.setAmplitude(NumUtil.change(values[43])); //振幅
            bean.setPeRatioTTM(NumUtil.change(values[39])); //市盈率
            bean.setPeRatio(NumUtil.change(values[46]));  //市净率
            bean.setTotalMarketCap(NumUtil.change(values[45]));   // 总市值（亿元）
            bean.setCirculatingCap(NumUtil.change(values[44]));   // 流通市值（亿元）
            bean.setDynamicPeRatio(NumUtil.change(values[52])); //动态市盈率
            bean.setStaticPeRatio(NumUtil.change(values[53])); //静态市盈率
            bean.setVolumeCompare(NumUtil.change(values[49])); //量比
            bean.setExchange(NumUtil.change(values[38])); //换手
            bean.setHighLimit(NumUtil.change(values[47])); //涨停价
            bean.setLowLimit(NumUtil.change(values[48])); //跌停价

            BigDecimal now = new BigDecimal(values[3]);
            String costPriceStr = bean.getCostPrise();
            if (StringUtils.isNotEmpty(costPriceStr)) {
                BigDecimal costPriceDec = new BigDecimal(costPriceStr);
                BigDecimal incomeDiff = now.add(costPriceDec.negate());
                if (costPriceDec.compareTo(BigDecimal.ZERO) <= 0) {
                    bean.setIncomePercent("0");
                } else {
                    BigDecimal incomePercentDec = incomeDiff.divide(costPriceDec, 5, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.TEN)
                            .multiply(BigDecimal.TEN)
                            .setScale(3, RoundingMode.HALF_UP);
                    bean.setIncomePercent(incomePercentDec.toString());
                }

                String bondStr = bean.getBonds();
                if (StringUtils.isNotEmpty(bondStr)) {
                    BigDecimal bondDec = new BigDecimal(bondStr);
                    BigDecimal incomeDec = incomeDiff.multiply(bondDec)
                            .setScale(2, RoundingMode.HALF_UP);
                    bean.setIncome(incomeDec.toString());
                }
            }

           log.info("{}",bean);
            resultArr.add(bean);
        }
        return resultArr;
//        Console.log(JSONUtil.toJsonStr(resultArr));
    }


    public void anylysisP(String result){
        List<StockBean> resultArr = parse(result);
        List<StockBean> highArr = new ArrayList<>();
        resultArr.forEach(obj->{
            if(obj.getPriceNow() == obj.getHighLimit()){
                highArr.add(obj);
            }
        });
        List<StockBean> otherArr = loadDataByFile("E:\\JavaProject\\stock\\src\\main\\resources\\data\\2024-12-11-P.txt");
        List<StockBean> lastHighArr = new ArrayList<>();
        List<StockBean> lianbanArr = new ArrayList<>(highArr);
        otherArr.forEach(obj->{
            if(obj.getPriceNow() == obj.getHighLimit()){
                lastHighArr.add(obj);
            }
        });
        lianbanArr.retainAll(lastHighArr);
        StringBuilder stringBuilder = new StringBuilder();
        String title = "### **今日共涨停"+highArr.size()+"只股票,其中连板股票"+lianbanArr.size()+"只**\n" ;
        stringBuilder.append(title);
        stringBuilder.append("- 名称-编码\n");
        for (int i = 0; i < highArr.size(); i++) {
            StockBean stockBean = highArr.get(i);
            stringBuilder.append(String.format("- %s-%s\n",stockBean.getName(),stockBean.getCode()));
        }
//        System.out.println(stringBuilder.toString());
        DingDingBot.sendMarkDown(title,stringBuilder.toString());
    }

}
